package com.song.shop.elasticsearch;

import com.alibaba.fastjson.JSONObject;
import com.song.shop.entity.Shop;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Song Yinghui
 * @date 2018/9/12
 * @Version 1.0
 */
public class ElasticSearchTest {

    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchTest.class);

    private static TransportClient client ;
    static {
        // try {
        // client = TransportClient.builder().build()  //5.0以上版本 初始化client方式改变，TransportClient类变为abstract
        //    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.232.128"), 9300));
        // } catch (UnknownHostException e) {
        //    e.printStackTrace();
        //   logger.error("",e);
        // }
        //}
    }

    public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(""),9300));

        /*client = TransportClient.build()  //5.0以上版本 初始化client方式改变，TransportClient类变为abstract
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.232.128"), 9300));*/
        return null ;
    }

    public void index() {
        //elasticSearch 2.4.0
        //5.0 以上可能不一样
        Shop shop = new Shop();
        shop.setShopName("shop22222");
        shop.setShopDesc("这是222一个描述文案");
        shop.setId("3233");

        Map map = new HashMap<String , String>();
        map.put("id","22");
        map.put("name", "这是key2");
        map.put("sex","这是value2");


        //JSONObject jsonObject = (JSONObject) JSONObject.toJSON(shop);
        IndexRequest request = new IndexRequest("shop","test");
        request.id(map.get("id").toString());
        request.source(map);
        //request.source(shop.toString().getBytes(Charset.forName("utf-8")));
        //request.source("value" , jsonObject);
        IndexResponse indexResponse = client.index(request).actionGet();
        //boolean created = indexResponse.isCreated();
      //  System.out.println("是否创建："+created);
    }

    public void search(){

        SearchRequest request = new SearchRequest();
        QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("key1" , "这是key"));
                                    //.must(QueryBuilders.matchQuery("other" , "三个"));


        //multiMatch匹配的是 多个字段包含这一个关键词
        QueryBuilder queryBuilder1 = QueryBuilders.boolQuery().must(QueryBuilders.multiMatchQuery("这是文案" , "key1" , "value.shopDesc"));

        SearchResponse searchResponse = client.prepareSearch("shop").setTypes("test")
                                        .setQuery(queryBuilder).setFrom(0).setSize(10).get();
        logger.info("结果：[{}]"  , searchResponse);
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit s : hits){
            logger.info("读取到的内容[{}]" , s.getSource().toString());
        }


       /* SearchRequest request = new SearchRequest();

        SearchResponse response = client.prepareSearch("song").setTypes("").setQuery(QueryBuilders.matchAllQuery())
                .setSearchType(SearchType.QUERY_THEN_FETCH).setExplain(true).get();
        QueryBuilder qb = QueryBuilders.queryStringQuery("song");

        //System.out.println(response);

        request.searchType("");
//        client.search();*/
    }

    public static void main(String[] args) {

        ElasticSearchTest elasticSearchTest = new ElasticSearchTest();
       // elasticSearchTest.index();
        elasticSearchTest.search();
    }

}
